package com.common.zrd.mark;

/**
 * @author zrd
 * @version 1.0
 * @date 2020/11/17 17:36
 */

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

public class TextWater {
    public static void main(String[] args) {
        //创建PdfDocument对象
        PdfDocument pdf = new PdfDocument();

        //加载示例文档
        pdf.loadFromFile("D:\\2.pdf");
        for (int i = 0; i < pdf.getPages().getCount(); i++) {
            //获取第一页
            PdfPageBase page = pdf.getPages().get(i);

            //调用insertWatermark方法插入文本水印
            insertWatermark(page, "1888655555");
        }

        //保存文档
        pdf.saveToFile("D:\\28.pdf");

        //保存为HTML格式
        pdf.saveToFile("D:\\ToHTML.html", FileFormat.HTML);
        //保存为Word格式
        pdf.saveToFile("D:\\ToWord.docx", FileFormat.DOCX);
        //保存为SVG格式
        pdf.saveToFile("D:\\ToSVG.svg", FileFormat.SVG);
        //保存为XPS格式
        pdf.saveToFile("D:\\ToXPS.xps", FileFormat.XPS);
    }

    static void insertWatermark(PdfPageBase page, String watermark) {
        Dimension2D dimension2D = new Dimension();
        dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 2,
                page.getCanvas().getClientSize().getHeight() / 3);
        PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
        brush.getGraphics().setTransparency(0.3F);
        brush.getGraphics().save();
        brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2,
                (float) brush.getSize().getHeight() / 2);
        brush.getGraphics().rotateTransform(-45);
        brush.getGraphics().drawString(watermark, new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.getViolet(), 0
                , 0, new PdfStringFormat(PdfTextAlignment.Center));
        brush.getGraphics().restore();
        brush.getGraphics().setTransparency(1);
        Rectangle2D loRect = new Rectangle2D.Float();
        loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize());
        page.getCanvas().drawRectangle(brush, loRect);
    }
}